<?php

session_start();

require_once ("../../../db.php");


if (!isset($_SESSION['uid']) || ($_SESSION['type'] != 'student')) {
    die('Not logged in as an student user');
}

$sql = 'SELECT * FROM groupparticipants WHERE participantid=?'; // find the group ID
$sth = $db->prepare($sql);
$sth->execute(array($_SESSION['uid']));
$row = $sth->fetch();
if ($row) {
    $sql = 'SELECT * FROM groupparticipants';   // select all students in a group
    $sth = $db->prepare($sql);
    $sth->execute();
    $row1 = $sth->fetchAll();
    $check = false;
    foreach ($row1 as $student) {
        if ($student[1] == $_POST['studid']) {  // checks if the student is in a group
            $check = true;
        }
    }
    if ($check == true) {
        echo json_encode(array('error' => 'Student er allerede i gruppe'));
    } else {
        $sql = 'INSERT INTO groupparticipants(groupid, participantid) VALUES (?, ?)'; // insert the student to group
        $sth = $db->prepare($sql);        
        $res = $sth->execute(array($row['groupid'], $_POST['studid']));
        if ($res) {
            echo json_encode(array('success' => 'Student ble lagt til'));
        } else {
            echo json_encode(array('error' => 'Student ble ikke lagt til'));
        }
    }
} else {
    echo json_encode(array('error' => 'Student ble ikke lagt til'));
}
?>